//
//  Loger3DLoginViewController.m
//  Longer3D
//
//  Created by wdj on 17/8/5.
//  Copyright (c) 2017年 . All rights reserved.

#import "Loger3DLoginViewController.h"
//#import "Loger3DMineViewController.h"
//#import "Loger3DForgetPassWordVC.h"
#import "Loger3DNewUserRegisterVC.h"
//#import "Longer3DNavigationController.h"
//#import "Loger3DTabBarController.h"

#import "MyscrollView.h"
//#import "PersonInfo.h"

//#import "MBProgressHUD+MJ.h"
#import "NSString+Check.h"
//#import "AFNetworking.h"
//#import "MobClick.h"
#import "PGTabBarController.h"

@interface Loger3DLoginViewController ()<UITextFieldDelegate>
@property (nonatomic,weak) UIButton *loginBtn;
@end

@implementation Loger3DLoginViewController{
    UITextField *_userNameTF;
    UITextField *_passwordTF;
    MyscrollView *backView;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage resizedImage:@"nav_redbg"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.contentMode = UIViewContentModeCenter;
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    backView = [[MyscrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    backView.userInteractionEnabled = YES;
    backView.bounces = NO;
    [self.view addSubview:backView];
    
    //设置背景图片
    [self setBackgroundImage];
    //设置账号等
    [self setAccount];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(backClick) image:@"back" highImage:@"back"];
    
    [Loger3DNotificationCenter addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

}


- (void)dealloc{
    [Loger3DNotificationCenter removeObserver:self];
}


- (void)backClick{

    [self.navigationController popViewControllerAnimated:YES];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)setBackgroundImage
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:backView.bounds];
//    imageView.image = [UIImage imageNamed:@"login_background"];
    [backView addSubview:imageView];
    
}

- (void)setAccount
{
    UIImageView *logoImageView = [[UIImageView alloc] init];
    logoImageView.size = CGSizeMake(80, 80);
    logoImageView.x = (self.view.width - logoImageView.width)/2;
    logoImageView.y = 30;
    logoImageView.backgroundColor = [UIColor clearColor];
    logoImageView.image = [UIImage imageNamed:@"icon_loginlogo"];
    [backView addSubview:logoImageView];

    //账号、密码相关设置
    UIView *usernameView = [[UIView alloc]initWithFrame:CGRectMake(12, logoImageView.frame.size.height +logoImageView.frame.origin.y + 30, ScreenWidth - 24, 96)];
    usernameView.layer.cornerRadius = 2;
    usernameView.backgroundColor = Loger3dColor(243, 246, 246, 1);
    [backView addSubview:usernameView];

    UIImageView *userlogo = [[UIImageView alloc]initWithFrame:CGRectMake(15, 14,20 , 20)];
    userlogo.image = [UIImage imageNamed:@"icon_loginUsername"];
    [usernameView addSubview:userlogo];
    
    _userNameTF = [[UITextField alloc]initWithFrame:CGRectMake(userlogo.frame.origin.x + userlogo.frame.size.width + 14, 0, ScreenWidth - 24 - 105, 48)];
    _userNameTF.textColor = [UIColor blackColor];
    _userNameTF.keyboardType = UIKeyboardTypeDecimalPad;
//    _userNameTF.placeholder = @"手机号";
    _userNameTF.text = @"13871530057";
    [usernameView addSubview:_userNameTF];

    
    CALayer* line = [CALayer layer];
    line.frame = CGRectMake(9, 48, usernameView.frame.size.width - 18, 1);
    line.backgroundColor = Loger3dColor(200,200,200,1).CGColor;
    [usernameView.layer addSublayer:line];
    
    UIImageView *passwordlogo = [[UIImageView alloc]initWithFrame:CGRectMake(15, line.frame.origin.y + 14, 20, 20)];
    passwordlogo.image = [UIImage imageNamed:@"icon_loginPassword"];
    [usernameView addSubview:passwordlogo];
    
    _passwordTF = [[UITextField alloc]initWithFrame:CGRectMake(userlogo.frame.origin.x + userlogo.frame.size.width + 14, 48, ScreenWidth - 24 - 105, 48)];
    _passwordTF.textColor = _userNameTF.textColor;
    _passwordTF.keyboardType = UIKeyboardTypeNamePhonePad;
    _passwordTF.placeholder = @"密码";
    _passwordTF.text = @"123456";
    [usernameView addSubview:_passwordTF];

    //登陆按钮
     UIButton * loginBTN = [[UIButton alloc]initWithFrame:CGRectMake(12,usernameView.frame.origin.y+usernameView.frame.size.height + 22, ScreenWidth - 24, 42)];
    self.loginBtn = loginBTN;
    [backView addSubview:loginBTN];
    
    _passwordTF.secureTextEntry = YES;
    [loginBTN setBackgroundColor:publicBtnColor];
    [loginBTN setTitle:@"登录" forState:UIControlStateNormal];
    loginBTN.layer.cornerRadius = 2;
    [loginBTN addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    
    //忘记密码
    UIButton *forget = [[UIButton alloc]initWithFrame:CGRectMake(0, loginBTN.frame.origin.y + loginBTN.frame.size.height + 30,ScreenWidth/3, 44)];
    [forget setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forget setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [forget addTarget:self action:@selector(forgetPassword) forControlEvents:UIControlEventTouchUpInside];
    forget.titleLabel.font = [UIFont systemFontOfSize:14];
    [backView addSubview:forget];
    
    //新用户注册
    UIButton  *registBtn = [[UIButton alloc]initWithFrame:CGRectMake( 2*ScreenWidth/3, forget.frame.origin.y, ScreenWidth/3, 44)];
    [registBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [registBtn setTitle:@"新用户注册" forState:UIControlStateNormal];
    registBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    registBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    
    UIImageView *registlogo = [[UIImageView alloc]initWithFrame:CGRectMake(110, 15, 13, 14)];
    registlogo.image = [UIImage imageNamed:@"new_user_registration"];
    [registBtn addSubview:registlogo];
    [registBtn addTarget:self action:@selector(newUserRegister) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:registBtn];

}


- (void)newUserRegister
{
    Loger3DNewUserRegisterVC *regist = [[Loger3DNewUserRegisterVC alloc]init];
    regist.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:regist animated:YES];
    
    
}

- (void)forgetPassword
{
//    Loger3DForgetPassWordVC *forgetpw = [[Loger3DForgetPassWordVC alloc]init];
//    forgetpw.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:forgetpw animated:YES];
    
    
}


-(void)login:(UIButton*)sender{
    
    if (![_userNameTF.text checkPhoneNumInput]) {
        [MBProgressHUD showError:@"请输入正确的手机号"];
        return;
    }
    
    NSMutableDictionary *para = [[NSMutableDictionary alloc] init];
    para[@"mobile"] = _userNameTF.text;
    para[@"password"] = _passwordTF.text;
    
    [XYNetworking POST:@"api/login" baseURL:LYT_BASE_URL params:para success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = (NSDictionary*)responseObject;
        if ([dict[@"code"] intValue] == 0) {
            //登陆成功,存下token到沙盒,跳转到主页
            [[NSUserDefaults standardUserDefaults] setObject:dict[@"token"] forKey:@"token"];
//            [self.navigationController dismissViewControllerAnimated:YES completion:^{
            
//            }];
//            UIWindow *window = [UIApplication sharedApplication].keyWindow;
//            window.rootViewController = [[PGTabBarController alloc] init];
            
            [self restoreRootViewController:[[PGTabBarController alloc] init]];
            
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showError:@"请检查网络"];
    }];
    
    
}



- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    // 动画的持续时间
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    // 键盘的frame
    CGRect keyboardEndF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
        if ( keyboardEndF.origin.y < (self.loginBtn.y + self.loginBtn.height)) { // 键盘的Y值已经远远超过了控制器view的高度
            
//            [UIView animateWithDuration:duration animations:^{
//                backView.contentOffset = CGPointMake(0,64 + keyboardEndF.size.height );
//                backView.contentSize = CGSizeMake(ScreenWidth, self.loginBtn.y + self.loginBtn.height + 64 + keyboardEndF.size.height);
//            }];

            [UIView animateWithDuration:duration animations:^{
                backView.contentOffset = CGPointMake(0,0);
                backView.contentSize = CGSizeMake(ScreenWidth, keyboardEndF.origin.y +20);
//                backView.contentOffset = CGPointMake(0, 64 +  keyboardEndF.size.height );
//                backView.contentSize = CGSizeMake(ScreenWidth, self.loginBtn.y + self.loginBtn.height + 64 + keyboardEndF.size.height);
            } completion:^(BOOL finished) {
                // 内间距 = btn的maxY + 键盘高度
                backView.contentOffset = CGPointMake(0, 64 +  keyboardEndF.size.height );
                backView.contentSize = CGSizeMake(ScreenWidth, self.loginBtn.y + self.loginBtn.height + 64 + keyboardEndF.size.height);
            }];
        }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [UIView animateWithDuration:0.25 animations:^{
        backView.contentOffset = CGPointMake(0,0);
        backView.contentSize = CGSizeMake(ScreenWidth, self.view.height);
        [self.view  endEditing:YES];
    }];
}

// 登陆后淡入淡出更换rootViewController
- (void)restoreRootViewController:(UIViewController *)rootViewController
{
    typedef void (^Animation)(void);
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    
    rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        [UIApplication sharedApplication].keyWindow.rootViewController = rootViewController;
        [UIView setAnimationsEnabled:oldState];
    };
    
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:nil];
}








































@end
